<template>
  <div class="container">
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <van-search
      v-model="keyword"
      placeholder="请输入搜索关键词"
      @search="onSearch"
    />
    <!-- 联想词列表 -->
    <van-cell-group class="suggest-box" v-if="keyword">
      <!-- span高亮联想关键词 -->
      <van-cell
        icon="search"
        @click="onSearch(word.replace(`<span>${keyword}</span>`, keyword))"
        v-for="(word, i) in suggestList"
        :key="i"
        ><p v-html="word"></p
      ></van-cell>
    </van-cell-group>
    <div class="history-box" v-else>
      <div class="head">
        <span>历史记录</span>
        <!-- 删除全部 -->
        <van-icon @click="all" name="delete"></van-icon>
      </div>
      <van-cell-group>
        <van-cell v-for="(his, i) in historyList" :key="his">
          <a class="word_btn">{{ his }}</a>
          <van-icon
            @click="delHistory(i)"
            class="close_btn"
            slot="right-icon"
            name="cross"
          />
        </van-cell>
      </van-cell-group>
    </div>
  </div>
</template>

<script>

// 1.存储用户的关键词搜索行为
// 1.设计数据结构
// 2.存储key名
import { suggest } from '../../api/search'
const TT_HS = 'TT_HS'
// localStorage.setItem(TT_HS, JSON.stringify(['小米', '华为']))
export default {
  name: 'search-index',
  data () {
    return {
      keyword: '',
      historyList: JSON.parse(localStorage.getItem(TT_HS)) || [],
      timer: null, // 定时器ID
      suggestList: []
    }
  },
  watch: {
    keyword () {
      // 清除定时器异步任务
      this.timer && clearTimeout(this.timer)
      // 函数防抖：当用户停止输入后600ms后处理联想词；
      // 如果600ms内再次输入内容，会清除上一次的任务，重新计时
      // 缓存定时器=>this.timer
      this.timer = setTimeout(async () => {
        try {
          const { data } = await suggest(this.keyword)
          console.log('关键词：', data.options)
          if (data.options === null) return
          // this.suggestList = data.options.map((word) => word.toLowerCase().replace(this.keyword, `<span>${this.keyword}</span>`))

          this.suggestList = data.options.map((words) => words.toLowerCase().replace(this.keyword, `<span>${this.keyword}</span>`)
          )
        } catch (error) {

        }
      }, 600)
    }
  },
  methods: {
    onSearch (val) {
      // console.log(val)
      if (!val) return
      const historySet = new Set(this.historyList)
      historySet.add(val)
      this.historyList = [...historySet]
      // 本地更新
      localStorage.setItem(TT_HS, JSON.stringify(this.historyList))
      // 跳转当前数据页面
      this.$router.push(`/search/result?q=${val}`)
    },
    delHistory (i) {
      // 内存删除
      this.historyList.splice(i, 1)
      // 硬盘删除 重新复制
      localStorage.setItem(TT_HS, JSON.stringify(this.historyList))
    },
    all () {
      // 内存删除
      this.historyList = []
      // 硬盘删除 重新复制
      localStorage.setItem(TT_HS, JSON.stringify(this.historyList))
    }
  }
}
</script>

<style scoped lang='less'>
.suggest-box {
  /deep/ .van-cell {
    padding: 10px 20px;
    color: #999;
    p {
      span {
        color: red;
      }
    }
  }
}
.history-box {
  padding: 0 20px;
  .head {
    line-height: 36px;
    color: #999;
    text-align: left;
    .van-icon {
      font-size: 16px;
      float: right;
      margin-top: 10px;
    }
  }
  .van-cell {
    padding: 10px 0;
  }
  .word_btn {
    color: #3296fa;
  }
  .close_btn {
    margin-top: 5px;
    color: #999;
  }
}
</style>
